package com.xlf.common.auth.util;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;

import com.xlf.common.core.constant.HttpStatus;
import com.xlf.common.core.exception.auth.JwtAuthenticationException;
import com.xlf.common.core.pojo.dto.JwtUserDetails;
import com.xlf.common.core.constant.CacheConstants;
import com.xlf.common.core.constant.Constants;
import com.xlf.common.core.util.IdUtils;
import com.xlf.common.core.util.ip.AddressUtils;
import com.xlf.common.core.util.ip.IpUtils;
import com.xlf.common.core.util.ServletUtils;
import com.xlf.common.core.util.StringUtils;
import com.xlf.common.redis.service.RedisCache;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * token验证处理
 *
 * @author xlf
 */
@Component
public class JwtTokenService
{

    // 令牌自定义标识
    private String header = "Authorization";

    // 令牌秘钥
    private String secret = "abcdefghijklmnopqrstuvwxyz";

    // 令牌有效期（默认30分钟）
    private int expireTime = 1440;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    /**
     * 解析token，解析不出来返回空值
     *
     * @return 用户信息
     */
    public JwtUserDetails getAuthentication(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            try //解析token
            {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);

                JwtUserDetails object = redisCache.getCacheObject(userKey);
//                System.out.println(object.toString());
                return object;
            }
            catch (Exception e)
            {
                //令牌解析不出来，可能是伪造的。
                // .方法一：抛出去让用户重新登录，这时前端记得要清token不然会无法登录，一直卡在这里
                // .方法二：直接放行，不给authentication,让security去处理即可
            }
        }
        return null;
    }

    /**
     * 通过token从redis拿用户信息
     * @param token
     * @return
     */
    public JwtUserDetails getAuthentication(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            try //解析token
            {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = null;
                try {
                    uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                } catch (Exception e) {
                    throw new JwtAuthenticationException("登录过期，请重新登录！", HttpStatus.UNAUTHORIZED);
                }
                String userKey = getTokenKey(uuid);

                JwtUserDetails object = redisCache.getCacheObject(userKey);
//                System.out.println(object.toString());
                if(object==null)
                    throw new JwtAuthenticationException("登录过期，请重新登录！", HttpStatus.UNAUTHORIZED);

                return object;
            }
            catch (Exception e)
            {

                //令牌解析不出来，1. 可能是伪造的。 2. token过期 3.系统错误
                // .方法一：抛出去让用户重新登录，这时前端记得要清token不然会无法登录，一直卡在这里
                // .方法二：直接放行，不给authentication,让security去处理即可
                //这里抛token过期，提醒用户重新登录。//当然也可能是redis宕机了。抛InternalAuthenticationServiceException。这里就不考虑了
                if(e instanceof AuthenticationException)
                    throw new JwtAuthenticationException("登录过期，请重新登录！",HttpStatus.UNAUTHORIZED);
                else
                    throw new JwtAuthenticationException(e.getMessage(),HttpStatus.UNAUTHORIZED);
            }
        }
        //无token
        return null;
    }

    /**
     * 更新令牌信息
     */
    public void updateAuthentication(JwtUserDetails jwtUserDetails)
    {
        if (StringUtils.isNotEmpty(jwtUserDetails.getUuid()))
        {
            // 根据uuid将loginUser缓存  getTokenKey拼一个前缀
            String userKey = getTokenKey(jwtUserDetails.getUuid());
            redisCache.setCacheObject(userKey, jwtUserDetails, expireTime, TimeUnit.MINUTES);
        }
    }

    /**
     * 删除用户身份信息
     @param uuid 存在JwtUserDetails的uuid
     */
    public void delAuthentication(String uuid)
    {
        if (StringUtils.isNotEmpty(uuid))
        {
            String userKey = getTokenKey(uuid);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌token，令牌token存一个uuid，把令牌token丢给前端
     * jwt认证的时候拿到前端传来的令牌token
     * 令牌token解析出uuid然后以uuid为key在redis拿JwtUserDetails
     * @param userDetails
     * @return 令牌token
     */
    public String createToken(JwtUserDetails userDetails)
    {
        String uuid = IdUtils.fastUUID();
        userDetails.setUuid(uuid);
        setUserAgent(userDetails);
        refreshToken(userDetails);
        //通过uuid生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, uuid);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param userDetails
     * @return 令牌
     */
    public void verifyToken(JwtUserDetails userDetails)
    {
        long expireTime = userDetails.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(userDetails);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param userDetails 登录信息
     */
    public void refreshToken(JwtUserDetails userDetails)
    {
        userDetails.setLoginTime(System.currentTimeMillis());
        userDetails.setExpireTime(userDetails.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存  getTokenKey拼一个前缀
        String userKey = getTokenKey(userDetails.getUuid());
        redisCache.setCacheObject(userKey, userDetails, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(JwtUserDetails jwtUserDetails)
    {
        if (StringUtils.isNotNull(jwtUserDetails) && StringUtils.isNotEmpty(jwtUserDetails.getUuid()))
        {
            refreshToken(jwtUserDetails);
        }
    }


    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }


    /**
     * 从request拿到获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 获取uuid的key。
     * @param uuid 存在JwtUserDetails的uuid
     * @return 作为redis缓存authentication的key
     */
    private String getTokenKey(String uuid)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(JwtUserDetails loginUser)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }
}
